<template>
  <div class="home-container">
    <div class="home-inner">
      <Category :categories="categories" @changeCategory="changeCategory" />
      <TopicList :list="topicList" />
      <div class="pager-wrapper">
        <Pager
          :current-page.sync="pageNumber"
          :total-page="totalPage"
          @change="changeCurrent"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { getCategory, getTopicList } from '@/api'
import Category from '@/views/Home/Category'
import TopicList from '@/views/Home/TopicList'
import Pager from '@/components/Pager'
export default {
  name: 'Home',
  components: {
    Category,
    TopicList,
    Pager
  },
  data() {
    return {
      categories: [],
      currentCategory: '',
      topicList: [],
      pageNumber: 1,
      totalRecord: 0,
      totalPage: 0
    }
  },

  mounted() {
    this.getCategoryApi()
  },

  methods: {
    // 获取所有的类别
    async getCategoryApi() {
      const res = await getCategory({ method: 'list' })
      this.categories = res.data
      this.currentCategory = this.categories[0].id
      this.getListApi()
    },

    // 类别切换
    changeCategory(id) {
      this.currentCategory = id
      this.pageNumber = 1
      this.totalPage = 0
      this.getListApi()
    },

    // 获取 topic 列表
    async getListApi() {
      const {
        data: { list, totalRecord, totalPage }
      } = await getTopicList({
        method: 'list',
        cId: this.currentCategory,
        page: this.pageNumber
      })
      this.topicList = list
      this.totalRecord = totalRecord
      this.totalPage = totalPage
    },

    // 页码改变
    changeCurrent() {
      this.getListApi()
    }
  }
}
</script>

<style scoped>
.home-container {
  max-width: 980px;
  margin: 0 auto;
  padding: 20px 0;
  border-radius: 4px;
}
.home-inner {
  min-height: 600px;
  background-color: #fff;
  box-shadow: 0 2px 3px rgba(0, 0, 0, 0.1);
  border-radius: 2px;
}
.pager-wrapper {
  padding: 20px 0 20px 30px;
}
</style>
